#include "cmdappdialog.h"
#include "ui_cmdappdialog.h"

#include <QScrollBar>
#include <QDebug>

CmdAppDialog::CmdAppDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::CmdAppDialog)
    , isFinished_(false)
    , isCancel_(false)
    , isReturn(false)
{
    ui->setupUi(this);

    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setWindowFlags(windowFlags() & ~Qt::WindowCloseButtonHint);

    connect(ui->cancelButton, &QPushButton::clicked, this, [=](){
        isCancel_= true;
    });
}

CmdAppDialog::~CmdAppDialog()
{
    delete ui;
}

void CmdAppDialog::setCommand(QString const& cmdApp)
{
    QFontMetrics metrics(font());
    ui->labelCommandName->setText(metrics.elidedText(cmdApp, Qt::ElideMiddle, width()));
}

void CmdAppDialog::progressText(QString const& text)
{
    setText(text);
}

void CmdAppDialog::finished()
{
    isFinished_ = true;
}

void CmdAppDialog::error(QString const& text)
{
     setText(text, true);
}

void CmdAppDialog::setText(QString const& text, bool isError)
{
    QString lineText = ui->labelProcess->text();
    QString outputText;
    int index = 0;

    if(leaveText.isEmpty())
        outputText = text;
    else
    {
        outputText = leaveText + text;
        leaveText.clear();
    }

    for(int i = 0; i < outputText.size(); i++)
    {
        if(outputText[i] == '\r')
        {
            QString subText = outputText.mid(index, i - index);
            if(lineText.isEmpty())
                lineText = subText;
            else
            {
                lineText.remove(0, subText.size());
                lineText.insert(0, subText);
            }
            ui->labelProcess->setText(lineText);
            index =  i + 1;
        }
        else if(outputText[i] == '\n')
        {
            if(lineText.isEmpty())
            {
                QString subText = outputText.mid(index, i - index + 1);
                ui->tbOutput->insertPlainText(subText);
                index =  i + 1;
            }
            else
            {
                QString subText = outputText.mid(index, i - index);
                ui->tbOutput->insertPlainText(lineText);
                ui->tbOutput->insertPlainText(subText);
                lineText.clear();
                ui->labelProcess->setText(lineText);
            }
        }
    }
    if(index < outputText.size())
    {
        if(index == 0)
            ui->labelProcess->setText(outputText);
        else
            leaveText = outputText.mid(index);
    }

    QScrollBar *bar = ui->tbOutput->verticalScrollBar();
    bar->setValue(bar->maximum());
}
